import { Destroyable, reactJson, Event, HasOwner } from "earthsdk3";
import { MyProjectManager } from "../MyProjectManager";
import { ObjResettingWithEvent } from "earthsdk3";
import { ESGeoPolygon, SceneTreeItem } from "earthsdk3";
import { newESJTreeParam } from "../esobjs/ESForest";
import { ESFeTreeEditing } from "../esobjs/ESFeTreeEditing";
import { getsceneObjNumfromSceneTree } from "../utils";
type pageType = { pageNum: number, pageSize: number, total: number, data: newESJTreeParam[] }
class SelectResetting extends Destroyable {
    constructor(selectTree: SelectTree, owner: MyProjectManager) {
        super();
        const sceneObject = owner.createSceneObject(ESGeoPolygon) as ESGeoPolygon
        sceneObject.stroked = true
        sceneObject.filled = false
        sceneObject.strokeWidth = 2
        sceneObject.editing = true

        {
            const updata = () => {
                if (sceneObject.editing) return;
                if (!sceneObject.points) return;
                selectTree.points = [...sceneObject.points, sceneObject.points[0]]
            }
            this.dispose(sceneObject.editingChanged.don(updata))
        }

        this.dispose(() => {
            selectTree.clear()
            sceneObject.editing = false
            sceneObject && owner.destroySceneObject(sceneObject);
        })
    }
}
export class SelectTree extends HasOwner<MyProjectManager> {
    get eSForest() { return this.owner.eSForestManager.eSForest }
    // 框选事件
    private _selectEvent = this.dv(new Event<[string]>());
    get selectEvent() { return this._selectEvent; }
    // 删除框选对象
    private _deleteSelect = this.dv(new Event());
    get deleteSelect() { return this._deleteSelect; }
    // 更新树种
    private _updateSelect = this.dv(new Event<[treeTypeIdString: string, treeId?: string]>());
    get updateSelect() { return this._updateSelect; }
    // 拾取处理
    private _selectResetting = this.dv(new ObjResettingWithEvent(this.selectEvent, (res) => {
        if (!res || res != "select") return undefined;
        this.clearSceneObject();
        return new SelectResetting(this, this.owner);
    }))
    get selectResetting() { return this._selectResetting; }
    // 多边形的点位
    private _points = this.dv(reactJson<any>([]));
    get points() { return this._points.value; }
    get pointsChanged() { return this._points.changed; }
    set points(value: any) { this._points.value = value; }
    // 分页信息
    private _pages = this.dv(reactJson<pageType>({
        pageNum: 1,
        pageSize: 10,
        total: 0,
        data: []
    }));
    get pages() { return this._pages.value; }
    get pagesChanged() { return this._pages.changed; }
    set pages(value: pageType) { this._pages.value = value; }

    private _sceneObjectMap = new Map<string, ESFeTreeEditing>(); // 存储场景对象的映射关系
    // 清除参数
    clear() {
        // this.eSForest.highlightTree([]);
        this.points = [];
        this.pages = {
            pageNum: 1,
            pageSize: 10,
            total: 0,
            data: []
        }
    }

    clearSceneObject() {
        this._sceneObjectMap.forEach(item => {
            const treeItem = this.owner.forestSceneTreeWrapper?.getTreeItemFromSceneObjId(item.id) as SceneTreeItem
            this.owner.forestSceneTreeWrapper?.destroySceneObjectTreeItem(treeItem)
        })
        this._sceneObjectMap.clear()
    }

    constructor(owner: MyProjectManager) {
        super(owner);
        this.ad(this.pointsChanged.don(() => {
            if (this.points.length < 3) return; // 至少三个点
            const temp = this.eSForest.queryByPolygon(this.points); // 拾取查询
            this.pages = {
                pageNum: 1,
                pageSize: 10,
                total: temp.length,
                data: temp
            }
        }))
        this.ad(this.deleteSelect.don(() => { // 删除框选对象
            this.eSForest.remove(this.pages.data.map((item: newESJTreeParam) => item.id));
            this.clear();
            this.clearSceneObject();
        }))
        this.ad(this.updateSelect.don((treeTypeIdString, treeId) => {
            const showIds = [];
            const treeTypeId = this.eSForest.treeTypesAll.findIndex(item => item.treeModelClassId == treeTypeIdString);
            for (let i = 0; i < this.pages.data.length; i++) {
                const item = this.pages.data[i];
                if (!treeId || item.id === treeId) {
                    this.createNewTree(treeTypeId, item);
                    showIds.push(item.id);
                    if (item.id === treeId) {
                        return;
                    }
                }
            }
            this.eSForest.treeShow(showIds, false);
        }));
    }
    createNewTree(treeTypeId: number, treeParam: newESJTreeParam) {
        if (this._sceneObjectMap.has(treeParam.id)) {
            const tempSceneObj = this._sceneObjectMap.get(treeParam.id)
            if (tempSceneObj) {
                tempSceneObj.url = this.eSForest.treeTypesAll[treeTypeId ?? treeParam.treeTypeId][this.owner.activeViewer && this.owner.activeViewer.getEngineType() == "ESCesiumViewer" ? "cesiumAssetServerPath" : "ueAsset"]
            }
            return;
        };
        let sceneObject: any
        const treeId = treeParam.id;
        const trees = this.owner.eSForestManager.eSForest.trees
        const tree = trees.find((tree: any) => tree.id == treeId)
        if (!tree) return;
        const { id, treeType, position, guanfu, xiongjing, zhixiagao, shugao } = tree;
        sceneObject = this.owner.createSceneObject(ESFeTreeEditing, id) as ESFeTreeEditing
        this._sceneObjectMap.set(treeId, sceneObject);
        sceneObject.dispose(() => {
            this.eSForest.treeShow([treeId], true);
            this._sceneObjectMap.delete(treeId);
        })
        sceneObject.position = treeParam.location;
        sceneObject.plotId = this.owner.eSForestManager.esForestPlotId
        sceneObject.time = this.owner.eSForestManager.esForestTime
        sceneObject.treeModelClassName = treeType
        sceneObject.shugao = shugao
        sceneObject.xiongjing = xiongjing
        sceneObject.zhixiagao = zhixiagao
        // @ts-ignore
        sceneObject.dongxiguanfu = guanfu[0]
        // @ts-ignore
        sceneObject.nanbeiguanfu = guanfu[1]
        sceneObject.scale = treeParam.scale
        sceneObject.url = this.eSForest.treeTypesAll[treeTypeId ?? treeParam.treeTypeId][this.owner.activeViewer && this.owner.activeViewer.getEngineType() == "ESCesiumViewer" ? "cesiumAssetServerPath" : "ueAsset"]
        sceneObject.rotation = treeParam.rotation ?? [0, 0, 0];
        const treeItem = this.owner.createdTreeItem(this.owner.forestSceneTreeWrapper)
        treeItem.sceneObject = sceneObject;
        const name = sceneObject.treeModelClassName
        const num = getsceneObjNumfromSceneTree(sceneObject.typeName, this.owner.forestSceneTreeWrapper);
        treeItem.name = `编辑_${name}(${num})`
        this.owner.forestSceneTreeWrapper?.uiTree.clearAllSelectedItems()
        treeItem.uiTreeObject.selected = true
    }
}